package com.zzw.demo.text_A;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzw.demo.util.KafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

public class Text04 {
    public static void main(String[] args) throws Exception {
        //在 DWD 层中，使用状态编程识别出新老用户。如果用户首次下单，则标记为新用户；否则标记为老用户，并在输出流中发送到相应的 Kafka 主题中（8分）
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置并行度
        env.setParallelism(1);
        //读取Kafka的数据源
        FlinkKafkaConsumer<String> consumer = KafkaUtil.kafkaSource("dwd_order_info", "text04");
        //转换成数据流
        DataStreamSource<String> dwdOrderInfo = env.addSource(consumer);
        SingleOutputStreamOperator<JSONObject> filter = dwdOrderInfo.map(x -> {
                    return JSONObject.parseObject(x);
                })
                .filter(x -> x.getJSONObject("after").getString("user_id") != null)
                .keyBy(x -> x.getJSONObject("after").getString("user_id"))
                .filter(new RichFilterFunction<JSONObject>() {
                    private transient ValueState<String> state;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> descriptor = new ValueStateDescriptor<>("date", String.class);
                        state = getRuntimeContext().getState(descriptor);
                    }

                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String firstDate = state.value();
                        // 用户状态,0表示老用户,1表示新用户
                        if (StringUtils.isEmpty(firstDate)) {
                            state.update("1");
                            value.put("is_new", "1");
                        } else {
                            value.put("is_new", "0");
                        }
                        return true;
                    }
                });
        //传入kafka
        filter.map(x->{return JSON.toJSONString(x);}).addSink(KafkaUtil.kafkaProducer("dwd_order_info_is_new"));

        //执行程序
        env.execute();
    }
}































































































































